package com.bstek.pms.tools.view.login;

import com.bstek.pms.tools.model.User;
import com.bstek.pms.tools.service.LoginService;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @Description 登录控制类
 * @Author hans
 * @CreateDate 2020-6-27
 */
public class LoginController implements Initializable {

    AbstractApplicationContext context=new ClassPathXmlApplicationContext("resources/conf/applicationContext.xml");

    @FXML
    private TextField username ;
    @FXML
    private TextField password ;
    @FXML
    private Label error;
    @FXML
    private VBox loginWindow;

    public LoginService loginService=context.getBean(LoginService.class);

    @FXML
    public void login(ActionEvent event){
        error.setText("");

        String userName=username.getText();
        String pwd=password.getText();
        User user=new User();
        user.setPassword(pwd);
        user.setName(userName);
        user=loginService.findUserByName(user);
        if (user!=null){
            if (user.getId()>0){
                System.out.println("登陆成功");
                //TODO 将用户登录信息保存到缓存中，并在主页底部栏显示
                Stage stage= (Stage) loginWindow.getScene().getWindow();
                stage.close();//关闭窗口
            }
        }else{
            error.setText("登录失败");
            System.out.println("登录失败");
        }

    }

    /**
     * 关闭登录窗口，回到主界面
     * @param event
     */
    @FXML
    public void exit(ActionEvent event){
        // Platform.exit();//退出应用程序
        Stage stage= (Stage) loginWindow.getScene().getWindow();
        stage.close();//关闭窗口
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }
}
